Undo & Redo

클래스 내에 생성되는 모든 Memento를 저장한다면, 커맨드 디자인 패턴의 구현에서와 같이
되돌리기(Undo)와 다시하기(Redo) 작업이 가능해진다.
class BankAccount2{
int balance=0;
vector<shared_ptr<Memento>> changes;
int current;
public:
explicit BankAccount2(const int balance): balance(balance){
changes.emplace_back(make_shared<Momento>(balance));
current=0;
} //
shared_ptr<Momento> deposit(int amount){
balance+=amount;
auto m=make_shared<Momento>(balance);
changes.push_back(m);
++current;
return m;
}
void restore(const shared_ptr<Memonto>& m){
if(m){
balance=m->balance;
changes.push_back(m);
current=changes.size()-1;
}
}
shared_ptr<Momento> undo(void){
if(current>0){
--current;
auto m=changes[current];
balance=m->balance;
return m;
}
return {}; // default shared_ptr (nullptr )
}
shared_ptr<Momento> redo(void){
if(current+1<changes.size()){
++current;
auto m=changes[current];
balance=m->balance;
return m;
}
return {};
}
};